<template>
  <div class="shop-form">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      size="default"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="店铺名称" prop="shopName">
            <el-input
              v-model="formData.shopName"
              placeholder="请输入店铺名称"
              maxlength="100"
              show-word-limit
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="店铺编码" prop="shopCode">
            <el-input
              v-model="formData.shopCode"
              placeholder="系统自动生成"
              readonly
              disabled
              style="background-color: #f5f7fa;"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="店铺类型" prop="shopType">
            <el-select v-model="formData.shopType" placeholder="请选择店铺类型" style="width: 100%">
              <el-option label="餐饮" :value="1" />
              <el-option label="零售" :value="2" />
              <el-option label="服务" :value="3" />
              <el-option label="其他" :value="4" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属社区" prop="communityId">
            <el-select v-model="formData.communityId" placeholder="请选择社区" style="width: 100%">
              <el-option
                v-for="community in communityList"
                :key="community.id"
                :label="community.communityName"
                :value="community.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="所属楼栋" prop="buildingId">
            <el-select v-model="formData.buildingId" placeholder="请选择楼栋" style="width: 100%">
              <el-option
                v-for="building in buildingList"
                :key="building.id"
                :label="building.buildingName"
                :value="building.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属单元" prop="unitId">
            <el-select v-model="formData.unitId" placeholder="请选择单元" style="width: 100%">
              <el-option
                v-for="unit in unitList"
                :key="unit.id"
                :label="unit.unitName"
                :value="unit.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="房间号" prop="roomNumber">
            <el-input
              v-model="formData.roomNumber"
              placeholder="请输入房间号"
              maxlength="50"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="楼层号" prop="floorNumber">
            <el-input-number
              v-model="formData.floorNumber"
              placeholder="请输入楼层号"
              :min="1"
              :max="100"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="店铺面积" prop="area">
            <el-input-number
              v-model="formData.area"
              placeholder="请输入店铺面积"
              :min="0"
              :max="10000"
              :precision="2"
              style="width: 100%"
            />
            <template #suffix>㎡</template>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="租金价格" prop="rentPrice">
            <el-input-number
              v-model="formData.rentPrice"
              placeholder="请输入租金价格"
              :min="0"
              :max="100000"
              :precision="2"
              style="width: 100%"
            />
            <template #suffix>元</template>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="联系人" prop="contactPerson">
            <el-input
              v-model="formData.contactPerson"
              placeholder="请输入联系人"
              maxlength="50"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系电话" prop="contactPhone">
            <el-input
              v-model="formData.contactPhone"
              placeholder="请输入联系电话"
              maxlength="20"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="营业执照" prop="businessLicense">
            <el-input
              v-model="formData.businessLicense"
              placeholder="请输入营业执照号"
              maxlength="100"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="formData.status">
              <el-radio :value="1">启用</el-radio>
              <el-radio :value="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="formData.remark"
          type="textarea"
          placeholder="请输入备注信息"
          :rows="3"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>

      <!-- 店铺图片上传 -->
      <el-form-item label="店铺图片" prop="images">
        <ImageUpload
          v-model="imageList"
          :upload-type="'SHOP_IMAGE'"
          :upload-source="'WEB'"
          :multiple="true"
          :max-size="10"
          :allowed-types="['jpg', 'jpeg', 'png', 'gif']"
          :limit="9"
          tip="请上传店铺图片，支持jpg、jpeg、png、gif格式，最大10MB，最多9张"
          @on-success="handleImageSuccess"
          @on-error="handleImageError"
          @on-change="handleImageChange"
        />
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <div class="form-actions">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submitting">
        {{ mode === 'add' ? '新增' : '保存' }}
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch, nextTick } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { shopApi } from '@/api/shop'
import { communityApi } from '@/api/community'
import { buildingApi } from '@/api/building'
import { unitApi } from '@/api/unit'
import ImageUpload from '@/components/ImageUpload.vue'
import type { ShopDetail as ShopVO, ShopFormData, FileInfo } from '@/api/shop'
import type { CommunityData as CommunityVO } from '@/api/community'
import type { BuildingData as BuildingVO } from '@/api/building'
import type { UnitData as UnitVO } from '@/api/unit'
import type { ImageInfo } from '@/views/region/shop/types'

// Props
interface Props {
  shopId?: number | null
  mode: 'add' | 'edit'
}

const props = defineProps<Props>()

// Emits
const emit = defineEmits<{
  success: []
  cancel: []
}>()

// 响应式数据
const formRef = ref<FormInstance>()
const submitting = ref(false)
const communityList = ref<CommunityVO[]>([])
const buildingList = ref<BuildingVO[]>([])
const unitList = ref<UnitVO[]>([])
const imageList = ref<ImageInfo[]>([])

// 表单数据
const formData = reactive<ShopFormData>({
  shopName: '',
  shopCode: '', // 新增时为空，由后端自动生成
  shopType: 1,
  communityId: undefined as number | undefined,
  buildingId: undefined as number | undefined,
  unitId: undefined as number | undefined,
  roomNumber: '',
  floorNumber: 1,
  area: 0,
  rentPrice: 0,
  contactPerson: '',
  contactPhone: '',
  businessLicense: '',
  remark: '',
  status: 1, // 状态：1-启用
  images: [] // 店铺图片信息列表（FileInfoDTO格式）
})

// 表单验证规则
const formRules: FormRules = {
  shopName: [
    { required: true, message: '请输入店铺名称', trigger: 'blur' },
    { min: 2, max: 100, message: '店铺名称长度在2到100个字符', trigger: 'blur' }
  ],
  shopCode: [
    // 店铺编码由系统自动生成，无需用户输入验证
  ],
  shopType: [
    { required: true, message: '请选择店铺类型', trigger: 'change' }
  ],
  communityId: [
    { required: true, message: '请选择所属社区', trigger: 'change' }
  ],
  contactPhone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

// 计算属性
const isEdit = computed(() => props.mode === 'edit')

// 生命周期
onMounted(() => {
  loadCommunityList()
  if (isEdit.value && props.shopId) {
    loadShopInfo()
  }
})

// 方法
// 解析图片信息列表（FileInfoDTO格式）
const parseImageInfoList = (imageInfoList: FileInfo[]): ImageInfo[] => {
  if (!imageInfoList || !Array.isArray(imageInfoList) || imageInfoList.length === 0) {
    return []
  }
  
  return imageInfoList.map((fileInfo: FileInfo, index: number) => ({
    uid: fileInfo.id || `existing-${index}`,
    id: fileInfo.id || `existing-${index}`,
    url: fileInfo.fileUrl || '',
    fileUrl: fileInfo.fileUrl || '',
    name: fileInfo.fileName || fileInfo.originalFileName || `图片${index + 1}`,
    fileName: fileInfo.fileName || fileInfo.originalFileName || `图片${index + 1}`,
    fileSize: fileInfo.fileSize || 0,
    fileType: fileInfo.fileType || '',
    uploadType: fileInfo.uploadType || '',
    uploadSource: fileInfo.uploadSource || '',
    status: fileInfo.status || 'success',
    createTime: fileInfo.createTime || '',
    fileExtension: fileInfo.fileExtension || '',
    originalFileName: fileInfo.originalFileName || '',
    filePath: fileInfo.filePath || '',
    isPublic: fileInfo.isPublic || true,
    downloadCount: fileInfo.downloadCount || 0,
    viewCount: fileInfo.viewCount || 0,
    sortOrder: fileInfo.sortOrder || 0
  }))
}

const loadCommunityList = async () => {
  try {
    const response = await communityApi.getCommunityList({})
    if (response.code === 200) {
      communityList.value = response.data || []
    } else {
      ElMessage.error(response.message || '加载社区列表失败')
    }
  } catch (error) {
    ElMessage.error('加载社区列表失败')
    console.error('加载社区列表失败:', error)
  }
}

const loadBuildingList = async (communityId: number) => {
  try {
    const response = await buildingApi.getBuildingsByCommunity(communityId)
    if (response.code === 200) {
      buildingList.value = response.data || []
    } else {
      ElMessage.error(response.message || '加载楼栋列表失败')
    }
  } catch (error) {
    ElMessage.error('加载楼栋列表失败')
    console.error('加载楼栋列表失败:', error)
  }
}

const loadUnitList = async (buildingId: number) => {
  try {
    const response = await unitApi.getUnitsByBuilding(buildingId)
    if (response.code === 200) {
      unitList.value = response.data || []
    } else {
      ElMessage.error(response.message || '加载单元列表失败')
    }
  } catch (error) {
    ElMessage.error('加载单元列表失败')
    console.error('加载单元列表失败:', error)
  }
}

const loadShopInfo = async () => {
  if (!props.shopId) return
  
  try {
    console.log('开始加载店铺信息，shopId:', props.shopId)
    const response = await shopApi.getShopDetail(props.shopId)
    console.log('店铺详情API响应:', response)
    
    // 检查响应结构
    if (response && response.code === 200 && response.data) {
      const shop = response.data
      console.log('店铺详情数据:', shop)
      
      // 安全地更新表单数据，处理可能的null/undefined值，确保数字字段类型正确
      Object.assign(formData, {
        shopName: shop.shopName || '',
        shopCode: shop.shopCode || '',
        shopType: Number(shop.shopType) || 1,
        communityId: shop.communityId || undefined,
        buildingId: shop.buildingId || undefined,
        unitId: shop.unitId || undefined,
        roomNumber: shop.roomNumber || '',
        floorNumber: Number(shop.floorNumber) || 1,
        area: Number(shop.area) || 0,
        rentPrice: Number(shop.rentPrice) || 0,
        contactPerson: shop.contactPerson || '',
        contactPhone: shop.contactPhone || '',
        businessLicense: shop.businessLicense || '',
        remark: shop.remark || '',
        images: shop.imageInfoList || [] // 加载店铺图片信息（FileInfoDTO格式）
      })
      
      // 解析图片信息并设置到imageList
      imageList.value = parseImageInfoList(shop.imageInfoList || [])
      
      console.log('加载的图片信息:', shop.imageInfoList)
      console.log('设置到imageList的图片信息:', imageList.value)
      
      console.log('表单数据已更新:', formData)
      
      // 加载关联数据
      if (shop.communityId) {
        await loadBuildingList(shop.communityId)
        if (shop.buildingId) {
          await loadUnitList(shop.buildingId)
        }
      }
    } else {
      console.error('API响应错误:', response)
      ElMessage.error(response?.message || '加载店铺信息失败')
    }
  } catch (error: any) {
    console.error('加载店铺信息异常:', error)
    
    // 处理业务错误
    if (error && error.isBusinessError) {
      ElMessage.error(error.message || '加载店铺信息失败')
    } else {
      ElMessage.error('加载店铺信息失败')
    }
  }
}

// 图片上传成功回调
const handleImageSuccess = (response: any, file: any, fileList: any[]) => {
  console.log('图片上传成功:', response, file, fileList)
  ElMessage.success('图片上传成功')
}

// 图片上传失败回调
const handleImageError = (error: any, file: any, fileList: any[]) => {
  console.error('图片上传失败:', error, file, fileList)
  ElMessage.error('图片上传失败')
}

// 图片变化回调
const handleImageChange = (file: any, fileList: any[]) => {
  console.log('图片变化:', file, fileList)
  console.log('当前imageList:', imageList.value)
  
  // 更新imageList
  imageList.value = fileList
  
  // 将图片列表转换为FileInfoDTO格式
  try {
    const imageInfoList: FileInfo[] = fileList.map((img: any) => ({
      id: img.id || img.uid || `shop_image_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
      fileName: img.fileName || img.name || '',
      fileUrl: img.fileUrl || img.url || '',
      fileSize: img.fileSize || 0,
      uploadType: 'SHOP_IMAGE',
      uploadSource: 'WEB',
      status: img.status || 'success',
      createTime: img.createTime || new Date().toISOString(),
      fileType: img.fileType || 'image/jpeg',
      fileExtension: img.fileExtension || (img.fileName ? img.fileName.split('.').pop() : 'jpg'),
      originalFileName: img.originalFileName || img.fileName || img.name || '',
      filePath: img.filePath || img.fileUrl || img.url || '',
      isPublic: img.isPublic !== false,
      downloadCount: img.downloadCount || 0,
      viewCount: img.viewCount || 0,
      sortOrder: img.sortOrder || 0
    }))
    
    formData.images = imageInfoList
    console.log('转换后的图片FileInfoDTO格式:', formData.images)
  } catch (error) {
    console.error('转换图片数据失败:', error)
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    submitting.value = true
    
    if (isEdit.value && props.shopId) {
      // 编辑店铺 - 包含图片信息，不发送店铺编码，保持原有编码
      const { shopCode, ...updateData } = formData
      const response = await shopApi.updateShop(props.shopId, updateData)
      if (response.code === 200) {
        ElMessage.success('编辑成功')
        emit('success')
      } else {
        ElMessage.error(response.message || '编辑失败')
      }
    } else {
      // 新增店铺 - 包含图片信息，不发送店铺编码，由后端自动生成
      const { shopCode, ...createData } = formData
      // 创建完整的createData对象
      const fullCreateData: ShopFormData = {
        ...createData,
        shopCode: shopCode || ''
      }
      const response = await shopApi.createShop(fullCreateData)
      if (response.code === 200) {
        ElMessage.success('新增成功')
        emit('success')
      } else {
        ElMessage.error(response.message || '新增失败')
      }
    }
  } catch (error) {
    if (error !== false) {
      ElMessage.error('提交失败')
      console.error('提交失败:', error)
    }
  } finally {
    submitting.value = false
  }
}

const handleCancel = () => {
  emit('cancel')
}

// 监听社区变化
const handleCommunityChange = (communityId: number) => {
  formData.buildingId = undefined
  formData.unitId = undefined
  buildingList.value = []
  unitList.value = []
  
  if (communityId) {
    loadBuildingList(communityId)
  }
}

// 监听楼栋变化
const handleBuildingChange = (buildingId: number) => {
  formData.unitId = undefined
  unitList.value = []
  
  if (buildingId) {
    loadUnitList(buildingId)
  }
}

// 监听表单数据变化
const watchCommunityId = (newVal: number | null) => {
  if (newVal) {
    handleCommunityChange(newVal)
  }
}

const watchBuildingId = (newVal: number | null) => {
  if (newVal) {
    handleBuildingChange(newVal)
  }
}

// 使用watch监听
watch(() => formData.communityId, watchCommunityId)
watch(() => formData.buildingId, watchBuildingId)
</script>

<style scoped>
.shop-form {
  padding: 20px;
}

.form-actions {
  margin-top: 30px;
  text-align: center;
}

.form-actions .el-button {
  margin: 0 8px;
  min-width: 100px;
}

:deep(.el-form-item__label) {
  font-weight: 600;
  color: #606266;
}

:deep(.el-input__suffix) {
  color: #909399;
  font-size: 14px;
}
</style>
